<?php

namespace app\home\controller;

use think\Cookie;
use think\Db;

class Task extends Base
{
    //查询任务一级分类
    public function selFirstClassfy()
    {
        $list = Db::name('task_first_classfy')->field('id,title,case_img img,price,num,screenshots_num')->select();
        return outputJson(0, 'ok', ['list' => $list]);
    }

    //查询任务二级分类
    public function selSecendClassfy()
    {
        $lists['app'] = [];
        $lists['browser'] = [];
        $list = Db::name('task_secend_classfy')->field('id,title,img,type,content')->select();
        foreach ($list as $k => $val) {
            if ($val['type'] == 2 || $val['type'] == 3) {
                $lists['app'][$k] = $val;
            } else {
                $lists['browser'][$k] = $val;
            }
        }
        $lists['app'] = array_values($lists['app']);
        $lists['browser'] = array_values($lists['browser']);
        return outputJson(0, 'ok', $lists);
    }

    //发布任务
    public function releaseTask()
    {
        $data = input('post.');
        $info = [
            'uid' => $this->user['id'],
            'first_id' => $data['first_id'],
            'secend_id' => $data['secend_id'],
            'title' => $data['title'],
            'link' => $data['link'],
            'aabstract' => $data['abstract'],
            'install_pkename' => $data['install_pkename'],
            'unit_price' => $data['unit_price'],
            'num' => $data['num'],
            'receive_num' => 0,
            //'screenshots_num' => $data['screenshots_num'],
            'case_img' => json_encode($data['case_img']),
            'qrcode_img' =>$data['qrcode_img']?json_encode($data['qrcode_img']):'',
            'note' => $data['note'],
            'type' => $data['type'],
            'end_time' => $data['end_time'],
            'start_time' => date('Y-m-d H:i:s'),
            'add_time' => date('Y-m-d H:i:s')
        ];
        //判断时间
        $times = strtotime($data['end_time']) - time();
        if ($times > 3 * 86400 || $times < 0) {
            return outputJson(100, '下线时间不能超过72小时');
        }
        //调用扣除发布的金额的接口
        $rate = [1 => 0.8, 2 => 1, 3 => 1.2];
        $account = $data['unit_price'] * $data['num'] * $rate[$data['type']] * 100;

        //查询余额
        $userEarn = userBalance(config('urls') . '/account/getinfo', $this->user['id']);
        if ($account > $userEarn['money'] * 100) {
            return outputJson(100, '余额不足');
        }

        //若成功则写入数据库 失败则重新发布
        $result = Db::name('task_release')->insert($info);
        if (!$result) {
            return outputJson(100, 'fail');
        }
        $id = Db::name('task_release')->max('id');
        $infos = [
            'url' => config('urls') . '/account/minusaccount',
            'income' => $account,
            'evt' => "发布" . $info['title'] . "任务" . $info['num'] . '份',
            'jobid' => $id,
            'uid' => $this->user['id']
        ];
        $re = minusaccount($infos);
        if (!$re) {
            return outputJson(100, 'fail', ['code' => 100, 'message' => '']);
        }

        return outputJson(0, 'ok');
    }

    //任务加票（加份数）
    public function taskAddNum()
    {
        $data = input('post.');
        if ($data['num'] <= 0) {
            return outputJson(100, 'fail');
        }

        $info = Db::name('task_release')->where('id', $data['id'])->field('id,title,unit_price,type')->find();
        //调用扣除发布的金额的接口
        $rate = [1 => 0.8, 2 => 1, 3 => 1.2];
        $account = $info['unit_price'] * $data['num'] * $rate[$info['type']] * 100;
        //查询余额
        $userEarn = userBalance(config('urls') . '/account/getinfo', $this->user['id']);
        if ($account > $userEarn['money'] * 100) {
            return outputJson(101, '余额不足');
        }
        $infos = [
            'url' => config('urls') . '/account/minusaccount',
            'income' => $account,
            'evt' => $info['title'] . "加" . $data['num'] . '份',
            'jobid' => $info['id'],
            'uid' => $this->user['id']
        ];
        $re = minusaccount($infos);
        if (!$re) {
            return outputJson(100, 'fail');
        }
        $rel = Db::name('task_release')->where('id', $data['id'])->setInc('num', $data['num']);
        $res = Db::name('task_release')->where('id', $data['id'])->setInc('receive_num', $data['num']);
        if ($rel === false || $res === false) {
            return outputJson(100, 'fail');
        }
        return outputJson(0, 'ok');
    }

    //发布的任务管理列表
    public function releasesTask()
    {
        $where['uid'] = $this->user['id'];
        if (input('status')) {
            $where['status'] = input('status');
        }
        $result = Db::name('task_release')->where($where)->field('id,title,unit_price,start_time,end_time,num,screenshots_num,status,add_time,reason,balance')->order('add_time desc')->select();
        foreach ($result as $key => $val){
            $result[$key]['taskOngoing'] = Db::name('task_receive')->where(['task_id'=>$val['id'],'status'=>1])->count();
            $result[$key]['taskAudit'] = Db::name('task_receive')->where(['task_id'=>$val['id'],'status'=>2])->count();
            $result[$key]['taskAuditSuc'] = Db::name('task_receive')->where(['task_id'=>$val['id'],'status'=>3])->count();
            $result[$key]['taskAuditFail'] = Db::name('task_receive')->where(['task_id'=>$val['id'],'status'=>4])->count();
            $result[$key]['taskAuditApl'] = Db::name('task_receive')->where(['task_id'=>$val['id'],'status'=>5])->count();
        }
        return outputJson(0, 'ok', $result);
    }

    //暂停任务
    public function suspendedTask()
    {
        $result = Db::name('task_release')->where(['id' => input('id')])->update(['status' => 4]);
        if ($result === false) {
            return outputJson(100, 'fail');
        }
        return outputJson(0, 'ok');
    }

    //恢复任务
    public function restoreTask()
    {
        $result = Db::name('task_release')->where(['id' => input('id')])->update(['status' => 2]);
        if ($result === false) {
            return outputJson(100, 'fail');
        }
        return outputJson(0, 'ok');
    }

    //下线任务
    public function offlineTask()
    {
        $result = Db::name('task_release')->where(['id' => input('id')])->update(['status' => 5]);
        if ($result === false) {
            return outputJson(100, 'fail');
        }
        return outputJson(0, 'ok');
    }

//    //接取任务
//    public function taskReceive()
//    {
//        $data = input('post.');
//        //查询已经做过的任务id 1进行中2审核中3审核通过4审核失败5申诉中6已取消7申诉成功8申诉失败9已放弃10未完成
//        $comTask = Db::name('task_receive')->where(['uid' => $this->user['id'], 'status' => ['in', [1,2, 3, 4, 5, 7, 8, 9, 11]]])->column('task_id');
//        if ($comTask) {
//            $where['id'] = ['not in', $comTask];
//        }
//
//        //获取发布的价格最高的id
//        $where['first_id'] = ['eq', $data['first_id']];
//        $where['uid'] = ['not in', $this->user['id']];
//        $where['status'] = ['eq', 2];
//        $where['receive_num'] = ['gt', 0];
//        $task = Db::name('task_release')->where($where)->field('id,abstract,case_img,qrcode_img,title,unit_price,num,type')->order('unit_price desc')->find();
//
//        //接受任务金额比例
//        $rale = Db::name('config')->where('type', 1)->value('content');
//        $masterAccount = sprintf("%.2f", ($task['unit_price'] * $rale) / 100);
//
//        if ($task && $task['num'] > 0) {
//            $info = [
//                'uid' => $this->user['id'],
//                'task_id' => $task['id'],
//                'first_id' => $data['first_id'],
//                'abstract' => $task['abstract'],
//                'case_img' => $task['case_img'],
//                'qrcode_img' => $task['qrcode_img'],
//                'unit_price' => $masterAccount,
//                'title' => $task['title'],
//                'type' => $task['type'],
//                'add_time' => date('Y-m-d H:i:s'),
//            ];
//            $res = Db::name('task_receive')->insertGetId($info);
//            //减去份数
//            $flag = Db::name('task_release')->where(['id' => $task['id']])->setDec('receive_num', 1);
//
//            if ($res && $flag !== false) {
//                return outputJson(0, 'ok', ['id' => $res]);
//            }
//            return outputJson(100, 'fail');
//        }
//        return outputJson(100, '暂无任务');
//    }

    //取消任务
    public function cancelTask()
    {
        $status = Db::name('task_receive')->where(['uid' => $this->user['id'], 'task_id' => input('id')])->value('status');
        if($status != 1){
            return outputJson(100, 'fail');
        }
        $res = Db::name('task_receive')->where(['uid' => $this->user['id'], 'task_id' => input('id')])->update(['if_start_task' => 0]);
        $userjobstatus = userjobstatus(config('xsurls') . '/job/userjobstatus', $this->user['id'], input('id'), 9);

        if ($userjobstatus['errcode'] == 0 && $res !== false) {
            updateredis(config('xsurls') . '/job/updateredis', $this->user['id']);
            return outputJson(0, 'ok');
        }
        return outputJson(100, 'fail');
    }

    //放弃任务
    public function giveUpTask()
    {
        $status = Db::name('task_receive')->where(['uid' => $this->user['id'], 'task_id' => input('id')])->value('status');
        if($status != 1){
            return outputJson(100, 'fail');
        }
        $res = Db::name('task_receive')->where(['uid' => $this->user['id'], 'task_id' => input('id')])->update(['if_start_task' => 0]);
        $userjobstatus = userjobstatus(config('xsurls') . '/job/userjobstatus', $this->user['id'], input('id'), 9);
       
        if ($userjobstatus['errcode'] == 0 && $res !== false) {
            updateredis(config('xsurls') . '/job/updateredis', $this->user['id']);
            return outputJson(0, 'ok');
        }
        return outputJson(100, 'fail');
    }

    //屏蔽任务
    public function shieldTask()
    {
        $status = Db::name('task_receive')->where(['uid' => $this->user['id'], 'task_id' => input('id')])->value('status');
        if($status != 1){
            return outputJson(100, 'fail');
        }
        $res = Db::name('task_receive')->where(['uid' => $this->user['id'], 'task_id' => input('id')])->update(['if_start_task' => 0]);
        $userjobstatus = userjobstatus(config('xsurls') . '/job/userjobstatus', $this->user['id'], input('id'), 11);
        if ($userjobstatus['errcode'] == 0 && $res !== false) {
            updateredis(config('xsurls') . '/job/updateredis', $this->user['id']);
            return outputJson(0, 'ok');
        }
        return outputJson(100, 'fail');
    }



    //未完成任务
    public function unfinishedTask()
    {
        $status = Db::name('task_receive')->where(['uid' => $this->user['id'], 'task_id' => input('id')])->value('status');
        if($status != 1){
            return outputJson(100, 'fail');
        }
        $res = Db::name('task_receive')->where(['uid' => $this->user['id'], 'task_id' => input('id')])->update(['if_start_task' => 0]);
        $userjobstatus = userjobstatus(config('xsurls') . '/job/userjobstatus', $this->user['id'], input('id'), 10);
        if ($userjobstatus['errcode'] == 0 && $res !== false) {
            updateredis(config('xsurls') . '/job/updateredis', $this->user['id']);
            return outputJson(0, 'ok');
        }
        return outputJson(100, 'fail');
    }

    //开始任务
    public function startTask()
    {
        $status = Db::name('task_receive')->where(['uid' => $this->user['id'], 'task_id' => input('id')])->value('status');
        if($status != 1){
            return outputJson(100, 'fail');
        }
        $res = Db::name('task_receive')->where(['uid' => $this->user['id'], 'task_id' => input('id')])->update(['if_start_task' => 1]);
        if ($res !== false) {
            return outputJson(0, 'ok');
        }
        return outputJson(100, 'fail');
    }

    //任务超时
    public function timeoutTask()
    {
        $status = Db::name('task_receive')->where(['uid' => $this->user['id'], 'task_id' => input('id')])->value('status');
        if($status != 1){
            return outputJson(100, 'fail');
        }
        $r = Db::name('task_receive')->where(['uid' => $this->user['id'], 'task_id' => input('id')])->update(['if_start_task' => 0,'add_time'=>date('Y-m-d H:i:s') ,'status'=>1]);
        if ($r === false) {
            return outputJson(100, 'fail');
        }
        updateredis(config('xsurls') . '/job/updateredis', $this->user['id']);
        return outputJson(0, 'ok');
//        if(input('type') == 1){
//            $where = [
//                'id' => input('id')
//            ];
//        }else{
//            $where = [
//                'uid' => $this->user['id'],
//                'task_id' => input('id')
//            ];
//        }

//        $res = Db::name('task_receive')->where($where)->field('task_id id,aabstract abstract,title,unit_price,add_time,status,img,audit_refuse_reason,audit_refuse_time,audit_time,appeal_reason,appeal_reason_time,appeal_refuse_reason,appeal_refuse_time,first_id,second_id,if_start_task ')->find();
//        $rs = Db::name('task_release')->where(['id' => $res['id']])->field('link,install_pkename,case_img,qrcode_img')->find();
//        $re = Db::name('task_secend_classfy')->where(['id' => $res['second_id']])->field('title sectitle,content')->find();
//        $res['installPkename'] = $rs['install_pkename'];
//        $res['link'] = $rs['link'];
//        $res['sectitle'] = $re['sectitle'] ;
//        $res['content'] = $re['content'] ;
//        $res['img'] = $res['img'] ? json_decode(json_decode($res['img'])) : [];
//        $res['case_img'] = $rs['case_img'] ? json_decode(json_decode($rs['case_img'])) : [];
//        $res['qrcode_img'] = $rs['qrcode_img'] ? json_decode(json_decode($rs['qrcode_img'])) : [];
//        //倒计时处理
//        $res['count_down'] = strtotime($res['add_time']) + 15 * 60 - time();
        return outputJson(0, 'ok', $res);
    }

    //提交任务
    public function complateTask()
    {
        $info = [
            'img' => json_encode(input('img')),
            'status' => 2
        ];
        $data = Db::name('task_receive')->where(['uid' => $this->user['id'], 'task_id' => input('id')])->field('id,unit_price,type,status')->find();
        if ($data['status'] != 1) {
            return outputJson(100, 'fail');
        }
        $type = Db::name('task_release')->where(['id' => input('id')])->value('type');
        if ($type == 1) {//免审直接发奖励
//            $result = addaccountTask(config('urls') . '/account/addaccount', $this->user['id'], ($data['unit_price'] * 100), $data['id']);
//            if (!$result) {
//                return outputJson(100, 'fail');
//            }
            $taskReceive = Db::name('task_receive')->where(['uid' => $this->user['id'], 'status' => ['eq', 3]])->select();
            if (count($taskReceive) == 1) {
                //新手任务----完成一次悬赏任务
                $signin = dailyTasks(config('urls') . '/account/addaccount', '完成一次悬赏任务', $this->user['id'], 20);
                if (!$signin) {
                    return outputJson(100, 'fail');
                }
            }
            $info['status'] = 3;
        }
        $res = Db::name('task_receive')->where(['uid' => $this->user['id'], 'task_id' => input('id')])->update($info);
        if ($res !== false) {
            updateredis(config('xsurls') . '/job/updateredis', $this->user['id']);
            return outputJson(0, 'ok');
        }
        return outputJson(100, 'fail');
    }

    //查询接取的任务详情
    public function taskDetail()
    {
        if(input('type') == 1){
            $where = [
                'id' => input('id')
            ];
        }else{
            $where = [
                'uid' => $this->user['id'],
                'task_id' => input('id')
            ];
        }
        $res = Db::name('task_receive')->where($where)->field('task_id id,aabstract abstract,title,unit_price,add_time,status,img,audit_refuse_reason,audit_refuse_time,audit_time,appeal_reason,appeal_reason_time,appeal_refuse_reason,appeal_refuse_time,first_id,second_id,if_start_task ')->find();
        $rs = Db::name('task_release')->where(['id' => $res['id']])->field('link,install_pkename,case_img,qrcode_img,type')->find();
        $re = Db::name('task_secend_classfy')->where(['id' => $res['second_id']])->field('title sectitle,content')->find();
        $res['installPkename'] = $rs['install_pkename'];
        $res['link'] = $rs['link'];
        $res['type'] = $rs['type'];
        $res['sectitle'] = $re['sectitle'] ;
        $res['content'] = $re['content'] ;
        $res['img'] = $res['img'] ? json_decode(json_decode($res['img'])) : [];
        $res['case_img'] = $rs['case_img'] ? json_decode(json_decode($rs['case_img'])) : [];
        $res['qrcode_img'] = $rs['qrcode_img'] ? json_decode(json_decode($rs['qrcode_img'])) : [];
        //倒计时处理
        $res['count_down'] = strtotime($res['add_time']) + 15 * 60 - time();
        return outputJson(0, 'ok', $res);
    }

    //上传图片
    public function unlodeImg()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('img');
        // 移动到框架应用根目录/public/uploads/ 目录下
        if (!$file) {
            return outputJson(100, 'fail');
        }
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if (!$info) {
            return outputJson(100, $file->getError());
        }
        $pathRead = $info->getSaveName();
        $path = '../public/uploads/' . $pathRead;
        $url = getImgUrls($path, $pathRead);
        return outputJson(0, 'ok', ['urls' => $url]);
    }

    //获取闲玩游戏列表
    public function getXwhHotGameList()
    {
        $url = "https://h5.17xianwan.com/try/API/try_api_list?";
        $data = [
            'ptype' => '2',
            'androidosv' => input('androidosv') ?? 0,
            'msaoaid' => input('msaoaid') ?? '',
            'appid' => '1531',
            'deviceid' => input('deviceid') ?? 0,
            'appsign' => $this->user['id'],
            'xwversion' => 2,
            'adtype' => input('adtype', '-99')
        ];
        $appsecret = "iv9h91nw7blzhuan";
        $data['keycode'] = md5($data['appid'] . $data['deviceid'] . $data['msaoaid'] . $data['androidosv'] . $data['ptype'] . $data['appsign'] . $appsecret);
        $url .= http_build_query($data);
        $re = object_arrays(json_decode(curlGet($url)));
        $list = [];
        if ($re['status'] == 0) {
            $list = $re['items'];
            foreach ($list as $k => $val) {
                $list[$k]['adname'] = explode('-', $val['adname']);
            }
        }
        return outputJson(0, 'ok', ['list' => $list]);
    }

}